package com.it.a04udpdemo3;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class ReceiveMessageDemo2 {
    public static void main(String[] args) throws IOException {
        MulticastSocket ms = new MulticastSocket(10000);
        //将当前本机，添加到224.0.0.1当中
        InetAddress address = InetAddress.getByName("224.0.0.1");
        ms.joinGroup(address);
        //接收数据
        byte[] bytes = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
        ms.receive(dp);
        //解析数据
        byte[] data = dp.getData();
        int len = dp.getLength();
        String ip = dp.getAddress().getHostAddress();
        String name = dp.getAddress().getHostName();
        System.out.println("IP为"+ip+"主机名为"+name+"发来消息："+new String(bytes,0,len));
        //释放资源
        ms.close();
    }
}
